#include "CanvasViewport.h"



CanvasViewport::CanvasViewport (Ptr< Document > pDoc, 
  Ptr< ViewportControl > pViewportControl) : _pDoc (pDoc), 
  _pViewportControl (pViewportControl)
{
  setMouseTracking (true);
  QImage patternImage (16, 16, QImage::Format_Indexed8);
  for (int v = 0; v < patternImage.height (); ++v)
  {
    uchar * patternLine = patternImage.scanLine (v);
    for (int u = 0; u < patternImage.width (); ++u)
    {
      if (u < patternImage.width () / 2 && v < patternImage.height () / 2)
        patternLine[u] = 255;
      else if (u >= patternImage.width () / 2 && v >= patternImage.height () / 2)
        patternLine[u] = 255;
      else
        patternLine[u] = 150;
    }
  }
  _backgroundPattern = QPixmap::fromImage (patternImage);
}



CanvasViewport::~CanvasViewport ()
{

}



void CanvasViewport::paintEvent (QPaintEvent * event)
{

  QPainter painter (this);

  // Draw background
  painter.save ();
  painter.setBrush (QColor (88, 88, 88));
  painter.drawRect (rect ());
  painter.restore ();

  // Draw canvas transparent background and border
  painter.save ();
  QBrush backgroundBrush;
  backgroundBrush.setTexture (_backgroundPattern);
  painter.setBrush (backgroundBrush);
  painter.setPen (QColor (0, 0, 0));
  painter.drawRect (_pViewportControl->getCanvasRegionInViewport ());
  painter.restore ();

  // Draw preview image
  if (_pDoc->isPreviewMode ())
    painter.drawImage (_pViewportControl->getPaintRegion (), 
      *_pDoc->getPreview (_pViewportControl->getImageRegion ()));
  else
    painter.drawImage (_pViewportControl->getPaintRegion (), 
      *_pDoc->getPreview (), _pViewportControl->getImageRegion ());

  // Let other components to draw their part
  QPoint imageO = _pViewportControl->imageToViewport (QPoint ());
  painter.translate (imageO);
  emit painting (painter);
}



void CanvasViewport::mouseMoveEvent (QMouseEvent * event)
{
  emit mouseMoved (event);
}



void CanvasViewport::mousePressEvent (QMouseEvent * event)
{
  emit mousePressed (event);
}



void CanvasViewport::mouseReleaseEvent (QMouseEvent * event)
{
  emit mouseReleased (event);
}



void CanvasViewport::resizeEvent (QResizeEvent * event)
{
  emit resized (event->size ());
}


